<template>
  <!-- 考试试卷 -->
  <div>
    <Header :type="1" :isShowColl="false">
      <!-- <template slot="left">
        <div class="go-back-btn click" @click="goBack">
          <i class="el-icon-arrow-left"></i>返回
        </div>
      </template> -->
      <template slot="center">
        <div>{{ $route.query.title }}</div>
      </template>
    </Header>

    <section
      class="main-container homework-paper w1200"
      :class="fix ? 'fix-container' : ''"
    >
      <div class="homework-paper-left katex-dom">
        <div class="potted-line" v-if="styleList[6] == 1">
          <div class="homework-info-left">
            <span class="homework-info-left-item">考号：<u></u> </span>
            <span class="homework-info-left-item">班级：<u></u> </span>
            <span class="homework-info-left-item">姓名：<u></u> </span>
            <span class="homework-info-left-item">学校：<u></u> </span>
          </div>
          <span class="potted-line-text potted-line-text3">装</span>
          <span class="potted-line-text potted-line-text2">订</span>
          <span class="potted-line-text potted-line-text1">线</span>
        </div>
        <div class="exam">
          <div class="exam-head">
            <div class="exam-title">
              <div class="exam-maintitle">
                {{ $route.query.title ? $route.query.title : paperInfo.title }}
              </div>
              <div
                class="exam-subtitle"
                v-if="styleList[0] == 1 && paperInfo.subtitle"
              >
                {{ paperInfo.subtitle }}
              </div>
            </div>
            <div class="exam-testinfo" v-if="styleList[1] == 1 && homeworkInfo">
              <span v-if="$route.query.isTest == 1">考试时间：60 分钟;</span>
              <!-- {{ parseInt(paperInfo.testTime / 60) }} -->
              <span
                >命题人:{{
                  homeworkInfo.teacher_name
                    ? homeworkInfo.teacher_name
                    : "智慧1+1AI老师"
                }}</span
              >
            </div>
            <div
              class="exam-studentinfo"
              v-if="styleList[2] == 1 && homeworkInfo"
            >
              <span class="studentinfo-item"
                >学校: <u> {{ homeworkInfo.organization_name }} </u></span
              >
              <span class="studentinfo-item"
                >姓名: <u> {{ homeworkInfo.student_name }} </u></span
              >
              <span class="studentinfo-item"
                >班级: <u> {{ homeworkInfo.class_name }} </u></span
              >
              <span class="studentinfo-item">考号: <u> </u></span>
            </div>
            <div class="exam-score" v-if="styleList[4] == 1">
              <table
                align="center"
                border="1"
                cellpadding="0"
                cellspacing="0"
                class="jcui-scoretable"
              >
                <tbody>
                  <tr>
                    <td width="80" align="center">题号</td>
                    <td
                      width="60"
                      align="center"
                      v-for="(questionList,
                      listIndex) in paperData.questionList"
                      :key="questionList.type"
                    >
                      <span v-if="listIndex === 0">一</span>
                      <span v-if="listIndex === 1">二</span>
                      <span v-if="listIndex === 2">三</span>
                      <span v-if="listIndex === 3">四</span>
                      <span v-if="listIndex === 4">五</span>
                      <span v-if="listIndex === 5">六</span>
                      <span v-if="listIndex === 6">七</span>
                    </td>
                    <td width="80" align="center">总分</td>
                  </tr>
                  <tr>
                    <td align="center">得分</td>
                    <td
                      v-for="questionList in paperData.questionList"
                      :key="questionList.type"
                    ></td>
                    <td></td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div
              class="exam-notice"
              style="display: block"
              v-if="styleList[7] == 1 && paperInfo.info"
            >
              <div class="exam-noticetip">注意事项：</div>
              <div
                class="exam-noticetext"
                v-html="paperInfo.info.replace(/[\r\n]/g, '<br />')"
              ></div>
            </div>
          </div>
          <div class="exam-body">
            <div
              class="exampart"
              v-for="(questionList, listIndex) in paperData.questionList"
              :key="questionList.typeId"
            >
              <div class="parthead" v-if="styleList[3] == 1">
                <div class="partheadbox exam-parthead" id="partheadbox1">
                  <div class="partname" id="partname1">
                    第
                    <span v-if="listIndex === 0">Ⅰ</span>
                    <span v-if="listIndex === 1">Ⅱ</span>
                    <span v-if="listIndex === 2">Ⅲ</span>
                    <span v-if="listIndex === 3">Ⅳ</span>
                    <span v-if="listIndex === 4">Ⅴ</span>
                    <span v-if="listIndex === 5">Ⅵ</span>
                    <span v-if="listIndex === 6">Ⅶ</span>
                    卷（{{ type[questionList.type].type }}）
                  </div>
                </div>
              </div>
              <div class="partbody">
                <div class="questype">
                  <div class="questypehead">
                    <div class="questypeheadbox">
                      <table
                        border="0"
                        cellpadding="0"
                        cellspacing="0"
                        style="width: 100%"
                      >
                        <tbody>
                          <tr>
                            <td width="1" v-if="styleList[5] == 1">
                              <div
                                class="
                                  jcui-catescore
                                  exam-catescore
                                  questypescore
                                "
                                id="questypescore"
                                style="width: 120px; display: block"
                              >
                                <table
                                  title="评分栏"
                                  border="1"
                                  cellpadding="0"
                                  cellspacing="0"
                                  style="border: 1px solid #666"
                                >
                                  <tbody>
                                    <tr>
                                      <td width="55" height="20" align="center">
                                        &nbsp;评卷人&nbsp;
                                      </td>
                                      <td width="55" align="center">
                                        &nbsp;得&nbsp;&nbsp;分&nbsp;
                                      </td>
                                    </tr>
                                    <tr>
                                      <td height="30" align="center">&nbsp;</td>
                                      <td>&nbsp;</td>
                                    </tr>
                                  </tbody>
                                </table>
                              </div>
                            </td>
                            <td style="text-align: left">
                              <div
                                class="
                                  exam-subjectnote
                                  questypetitle
                                  div-data-cate
                                "
                                cate="1"
                              >
                                <span v-if="listIndex === 0">一</span>
                                <span v-if="listIndex === 1">二</span>
                                <span v-if="listIndex === 2">三</span>
                                <span v-if="listIndex === 3">四</span>
                                <span v-if="listIndex === 4">五</span>
                                <span v-if="listIndex === 5">六</span>
                                <span v-if="listIndex === 6">七</span>
                                .{{ type[questionList.type].type }}（共{{
                                  questionList.list.length
                                }}小题）
                              </div>
                            </td>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  </div>
                  <div
                    class="reading-question grammar-question-list questypebody paper"
                  >
                    <ul
                      class="reading-question-list list-box sortable ulQuesGroup ui-sortable"
                    >
                      <li
                        v-for="(item, index) in questionList.list"
                        :key="item.questionId"
                        class="aitest-paper-question"
                        :id="'question' + listIndex + index"
                        :class="item.isFine == 0 ? 'question-del-bg' : ''"
                      >
                        <!-- v-for="(question, index) in paperData.questionList"
                          :key="item.questionId" -->
                        <!-- :totalIndex="paperData.questionList.length"
                          :nowIndex="index + 1" -->
                        <Question
                          :questionType="paperData.type"
                          :question="item"
                          :isAnswer="paperData.isAnswer"
                          :nowIndex="index + 1"
                          :classify="4"
                        ></Question>
                        <!-- <TestQuestion
                          :question="item"
                          :index="index"
                          :ref="`test-question-${listIndex}-${index}`"
                          @setStuAnswer="
                            (answerIndex, answerValue) => {
                              setStuAnswer(
                                listIndex,
                                index,
                                answerIndex,
                                answerValue
                              );
                            }
                          "
                          type="test"
                        ></TestQuestion> -->
                        <div
                          class="question-stauts"
                          v-if="item.isModify && item.isFine !== 0"
                        >
                          <span class="question-update">
                            <i class="el-icon-warning"></i> 此题已被修改
                          </span>
                        </div>
                        <div class="question-stauts" v-if="item.isFine == 0">
                          <span class="question-delete">
                            <i class="el-icon-error"></i> 此题已被删除
                          </span>
                        </div>
                      </li>
                    </ul>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="homework-paper-right knowledge-question" id="menu">
        <div class="paper-right-time">
          <div class="time-title">
            <span v-if="$route.query.isTest == 1">
              <i class="iconfont icon-naozhong"></i>
              剩余时间
            </span>
            <span v-else> 答题进度 </span>
          </div>

          <div class="time-contain" v-if="$route.query.isTest == 1">
            {{ residualTime | filterTime }}
          </div>
          <div class="question-progress">
            <div class="question-progress-box">
              <div
                class="question-progress-contain"
                :style="`width:${(answeredNum / totalNum) * 100}%`"
              >
                <span class="circle">
                  <span class="text">{{ answeredNum }}/{{ totalNum }}</span>
                </span>
              </div>
            </div>
          </div>
        </div>
        <div class="paper-right-contain knowledge-question-right">
          <div class="question-right-top">
            <!-- <i class="iconfont icon-datiqia"></i> -->
            <i class="el-icon-document" style="color: #ff9611;"></i>
            答题卡
            <!-- <el-button @click="checkA">看看</el-button> -->
          </div>
          <div class="question-right-card">
            <div class="scroll-box">
              <div
                v-for="(questionList, listIndex) in paperData.questionList"
                :key="listIndex"
              >
                <h4 class="type-list mb10">
                  <span v-if="listIndex === 0">一</span>
                  <span v-if="listIndex === 1">二</span>
                  <span v-if="listIndex === 2">三</span>
                  <span v-if="listIndex === 3">四</span>
                  <span v-if="listIndex === 4">五</span>
                  <span v-if="listIndex === 5">六</span>
                  <span v-if="listIndex === 6">七</span>.
                  <span>{{ type[questionList.type].type }}</span>
                </h4>
                <span
                  class="card-item click"
                  v-for="(question, index) in questionList.list"
                  :key="question.questionId"
                  :class="[
                    !question.isAnswer && isAnsweredQuestion(question)
                      ? 'checked-item'
                      : '',
                  ]"
                  @click="toTheQuestion(listIndex, index)"
                >
                  {{ index + 1 }}
                </span>
              </div>
            </div>
          </div>
          <div class="question-right-info">
            <div class="info-item info-item-checked">
              <span class="color-chunk"></span>
              已答
            </div>
            <div class="info-item">
              <span class="color-chunk"></span>
              未答
            </div>
          </div>
        </div>
        <div class="button-box">
          <el-button
            class="button button-border-primary"
            :disabled="!answeredNum"
            @click="saveHomework"
          >
            暂存作业
          </el-button>
          <el-button class="button button-bg-primary" @click="submit">
            提交作业
          </el-button>
        </div>
      </div>
    </section>
  </div>
</template>
<script>
import {
  getHomeworkList,
  getHomeworkInfo,
  getHomeworkParams,
} from "@/api/index.js";
// import {
//   getHomeworkQuestion,
// saveHomework,
// submitHomework,
// getHomeworkInfo,
// getTestPaper,
// getWeakSpotTest,
// getTestBeforeClass,
// postFinishTask,
// } from "@/api/1";
import Header from "@/components/Header";
import Question from "@/components/Question";
// import TestQuestion from "@/components/question/Index";
import {
  set_question_data,
  set_question_answer,
  is_answered_question,
} from "@/utils/question";

import { formatSeconds } from "@/utils/date";
export default {
  data() {
    return {
      paperData: {},
      type: {
        1: {
          type: "单选题",
          id: 1,
        },
        2: {
          type: "多选题",
          id: 2,
        },
        3: {
          type: "判断题",
          id: 3,
        },
        4: {
          type: "填空题",
          id: 4,
        },
        5: {
          type: "简答题",
          id: 5,
        },
      }, //题型
      paperQuestionList: [], //试卷题目列表
      paperInfo: {},
      homeworkInfo: null,
      // homeworkInfo:{
      //   teacherName:'徐磊他爹',
      //   organizationName:"徐氏中学",
      //   studentName:"徐磊",
      //   className:"四年级"
      // },
      //0副标题，1试卷信息，2考生信息，3分卷，4总分栏，5大题评分区，6装订线，7注意事项，8保密标记
      styleList: [],
      homeworkStudentId: null,
      isTest: this.$route.query.isTest,
      nowQuestionId: "question" + 0 + 0, //当前选中的题目
      residualTime: null, //剩余的时间
      submitReminderX: true,
      timer: null,
      grade: 0,
      longtime: "",
      time: 0,
      dialogVisible: false,
      fix: false,
      paper: {},
      classInfo: {},
      thePaperStartTime: null,
      submitReminder: true,
      totalNum: 0,
      isAnsweredQuestion: is_answered_question,
    };
  },
  computed: {
    answeredNum() {
      let num = 0;
      this.paperQuestionList.forEach((questionType) => {
        questionType.list.forEach((question) => {
          if (is_answered_question(question)) {
            num++;
          }
        });
      });
      return num;
    },
  },
  methods: {
    async getHomeworkParams() {
      const res = await getHomeworkParams({ id: this.$route.query.id });
      this.homeworkInfo = Object.assign({}, { ...res.data });
      console.log(res, "test");
    },
    checkA() {
      console.log(this.paperQuestionList);
    },
    setStuAnswer(listIndex, index, answerIndex, answerValue) {
      this.$set(
        this.paperQuestionList[listIndex].list[index].stuAnswer,
        answerIndex,
        answerValue
      );
    },
    //锚点定位
    toTheQuestion(listIndex, index) {
      this.nowQuestionId = "question" + listIndex + index;
      document.getElementById("question" + listIndex + index).scrollIntoView();
    },
    // 处理试卷信息 开始做试卷
    setPaperInfo(res) {
      //  if (res.data.question_list.length) {
      //   this.styleList = res.data.question_list.split(",");
      // } else {
      this.styleList = [1, 1, 1, 1, 1, 1, 1, 1, 1];
      // }
      console.log(121515);
      this.paperData = {
        startTime:res.data.start_time,
        isAnswer: false,
        id: this.$route.query.id,
        questionList: [],
      };
      this.paperData.questionList = res.data.question_list.map((item) => {
        if (item.type == 1) {
          //单选题
          item.list = item.list.map((item1) => {
            this.totalNum += 1;
            return {
              questionId: item1.question_id,
              title: item1.title,
              answerType: item.type,
              answerList: item1.answer.map((item) => {
                item.answer_id = item.id;
                return item;
              }),
              studentAnswer: [],
              inputNum: item1.inputNum,
            };
          });
          return item;
        } else if (item.type == 4) {
          item.list = item.list.map((item1) => {
            this.totalNum += 1;
            let newTitle = item1.title;
            let index = 1;
            let pos = newTitle.indexOf("_____");
            while (pos !== -1) {
              newTitle = newTitle.replace(
                /_{5}/,
                ` <input class='question-input' autocomplete="off" id='input-${item1.question_id}-${index}' onpaste = "return false";></input> `
              );
              index++;
              pos = newTitle.indexOf("_____");
            }
            item1.inputNum = index - 1;
            return {
              questionId: item1.question_id,
              title: newTitle,
              answerType: 2,
              answerList: undefined,
              //item1.answer.map((item) => {
              //   item.answer_id = item.id;
              //   return item;
              // }),
              studentAnswer: [],
              inputNum: item1.inputNum,
            };
          });
           return item
        } else {
          return item;
        }
      });
      if (this.paperData.startTime) {
        this.thePaperStartTime = this.paperData.startTime;
      } else {
        this.thePaperStartTime = new Date();
      }
      console.log(this.paperData, 15515);
      // this.setPaperQuery();
      // if (res.data.parameters) {
      //   this.styleList = res.data.parameters.split(",");
      // } else {
      //   this.styleList = [0, 0, 0, 0, 0, 0, 0, 0, 0];
      // }
      // res.data.questionList.forEach((item) => {
      //   item.list.forEach((question) => {
      //     this.totalNum++;
      //     question.typeId = item.typeId;
      //     question.questionList =
      //       question.questionList || question.sonQuestionList;
      //     set_question_data(question);
      //     if (question.studentAnswer && question.studentAnswer.length > 0) {
      //       question.studentAnswer.forEach((answer) => {
      //         if (item.typeId == 4) {
      //           question.stuAnswer[answer.order - 1] = answer.answer;
      //         }
      //         if (item.typeId == 3) {
      //           question.stuAnswer[answer.order - 1] = Number(answer.answer);
      //         }
      //         if (item.typeId == 1) {
      //           question.stuAnswer.push(answer.id);
      //         }
      //       });
      //     }

      //     question.questionList &&
      //       question.questionList.forEach((item) => {
      //         item.answer = item.answer || item.answers;
      //         set_question_data(item);
      //         if (item.studentAnswer && item.studentAnswer.length > 0) {
      //           item.studentAnswer.forEach((answer, index) => {
      //             if (item.typeId == 4) {
      //               item.stuAnswer[index] = answer.answer;
      //             }
      //             if (item.typeId == 3) {
      //               item.stuAnswer[index] = Number(answer.answer);
      //             }
      //             if (item.typeId == 1) {
      //               item.stuAnswer.push(answer.id);
      //             }
      //           });
      //         }
      //       });

      //     //   question.stuAnswer = [];
      //   });
      // });
      // this.paperInfo = res.data;
      // if (this.paperInfo.startTime) {
      //   this.thePaperStartTime = this.paperInfo.startTime;
      // } else {
      //   this.thePaperStartTime = new Date();
      // }
      // this.paperQuestionList = res.data.questionList;
      // this.$nextTick(() => {
      //   this.$setKatexDom();
      // });

      // if (this.isTest == 1) {
      //   if (res.data.startTime) {
      //     let time = parseInt(
      //       (new Date().getTime() -
      //         new Date(res.data.startTime.replace(/-/g, "/")).getTime()) /
      //         1000
      //     );

      //     if (time >= this.paperInfo.testTime) {
      //       // 已超时
      //       this.$alert("作业已超时", "提示", {
      //         confirmButtonText: "确定",
      //         callback: () => {
      //           this.$router.replace({
      //             name: "work",
      //           });
      //         },
      //       });
      //     } else {
      //       // 未超时
      //       this.residualTime = this.paperInfo.testTime - time;
      //       this.setTestTimer();
      //     }
      //   } else {
      //     this.residualTime = res.data.testTime;
      //     this.setTestTimer();
      //   }
      // }
    },
    setTestTimer() {
      let theEndTime = null;
      if (this.$route.query.endTime) {
        theEndTime = parseInt(
          (new Date(this.$route.query.endTime.replace(/-/g, "/")).getTime() -
            new Date().getTime()) /
            1000
        );
      } else if (!this.$route.query.endTime && this.$route.query.task) {
        let time =
          new Date().getFullYear() +
          "-" +
          (new Date().getMonth() + 1) +
          "-" +
          (new Date().getDate() + 1) +
          " 00:00:00";
        theEndTime = parseInt(
          (new Date(time.replace(/-/g, "/")).getTime() - new Date().getTime()) /
            1000
        );
      }
      if (theEndTime && theEndTime < this.residualTime) {
        this.residualTime = theEndTime;
      }
      this.timer = setInterval(() => {
        this.residualTime--;
        console.log(this.residualTime, "this.residualTime");
        //TODO
        if (
          this.residualTime > 0 &&
          this.residualTime <= 5 * 60 &&
          this.submitReminderX
        ) {
          this.submitReminderX = false;

          this.$alert(
            `考试时间还剩 ${formatSeconds(this.residualTime)},请及时提交试卷！`,
            "时间提示",
            {
              confirmButtonText: "确认",
              showClose: false,
            }
          )
            .then(() => {})
            .catch(() => {});
        }
        if (
          this.residualTime > 0 &&
          this.rsubmitGetesidualTime <= 20 &&
          this.submitReminder
        ) {
          this.submitReminder = false;
          this.$confirm("考试即将超时,请尽快交卷", "提示", {
            confirmButtonText: "交卷",
            cancelButtonText: "取消",

            showClose: false,
          })
            .then(() => {
              this.submitGet();
            })
            .catch(() => {});
        } else if (this.residualTime <= 0) {
          clearInterval(this.timer);
          this.$alert("考试已结束", "提示", {
            confirmButtonText: "确定",

            showClose: false,
          }).then(() => {
            this.$router.replace({
              name: "homeworkList",
            });
          });
        }
      }, 1000);
    },

    //提交作业
    submitGet() {
      let time = new Date();
      let useTime = parseInt(
        (new Date().getTime() -
          new Date(this.thePaperStartTime.replace(/-/g, "/")).getTime()) /
          1000
      );

      let timeStr =
        time.getFullYear() +
        "-" +
        (time.getMonth() + 1) +
        "-" +
        time.getDate() +
        " " +
        time.getHours() +
        ":" +
        time.getMinutes() +
        ":" +
        time.getSeconds();
      //来源
      let index = this.$store.getters.constDict.findIndex((item) => {
        if (this.$route.query.task && this.$route.query.taskType == 1) {
          return item.typeCode == "QUESTION_SOURCE" && item.name == "WEAK_SPOT";
        } else if (this.$route.query.task && this.$route.query.taskType == 2) {
          return (
            item.typeCode == "QUESTION_SOURCE" && item.name == "BEFORE_TEST"
          );
        } else if (this.$route.query.type == 2) {
          return (
            item.typeCode == "QUESTION_SOURCE" && item.name == "SIMULATION_TEST"
          );
        } else {
          return item.typeCode == "QUESTION_SOURCE" && item.name == "HOMEWORK";
        }
      });
      let source;
      if (index !== -1) {
        source = this.$store.getters.constDict[index].value;
      }
      let list = this.getStudentAnswerList();
      let data = {
        homeworkStudentId: this.homeworkStudentId,
        endTime: timeStr,
        source,
        list,
        useTime,
      };
      if (
        this.$route.query.firstTest &&
        this.$route.query.firstTest != "false"
      ) {
        data.type = 2;
      }
      this.$bus.$emit("openLoading");
      clearInterval(this.timer);
      // 提交试卷
      // submitHomework(data)
      //   .then((res) => {
      //     this.$bus.$emit("closeLoading");
      //     if (res.code == 200) {
      //       if (this.$route.query.task) {
      //         let data = {
      //           bookId: this.classInfo.bookId,
      //           type:
      //             this.$route.query.taskType == 1 ? "薄弱点练习" : "课前测试",
      //         };
      //         postFinishTask(data).then((res) => {
      //           if (res.code == 200) {
      //             console.log(res)
      //           }
      //         });
      //       }
      //       this.$router.replace({
      //         name: "lookPaper",
      //         query: {
      //           id: this.homeworkStudentId,
      //           title: this.$route.query.title
      //             ? this.$route.query.title
      //             : this.paperInfo.title,
      //           isTest: this.isTest,
      //         },
      //       });
      //     }
      //   })
      //   .catch(() => {
      //     this.$bus.$emit("closeLoading");
      //   });
    },
    handleScroll() {
      var scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.getElementById("app").scrollTop;
      if (scrollTop > 80) {
        this.fix = true;
      } else {
        this.fix = false;
      }
    },
    getStudentAnswerList() {
      let list = [];
      this.paperQuestionList.forEach((questionList, listIndex) => {
        questionList.list.forEach((question, index) => {
          let result = this.$refs[
            `test-question-${listIndex}-${index}`
          ][0].submit();
          list.push({
            questionId: question.questionId,
            answer: result.answer,
            typeId: question.typeId,
            sonQuestionList:
              result.questionList &&
              result.questionList.map((item) => {
                return {
                  questionId: item.questionId,
                  typeId: item.typeId,
                  sonAnswerList: item.answer,
                };
              }),
          });
          // if (result.answer.length > 0 || result.questionList) {

          // }
        });
      });
      return list;
    },
    // 暂存作业
    saveHomework() {
      let list = this.getStudentAnswerList();
      let params = {
        homeworkStudentId: this.homeworkStudentId,
        list,
      };
      // saveHomework(params).then((res) => {
      //   if (res.code == 200) {
      //     this.$alert("暂存作业成功");
      //   }
      // });
    },
    //提交作业验证
    submit() {
      console.log(this.paperData,"wenchengshuju");
      if (
        this.paperInfo.minSubmissionTime &&
        new Date().getTime() -
          new Date(this.paperInfo.startTime.replace(/-/g, "/")).getTime() <
          this.paperInfo.minSubmissionTime * 1000
      ) {
        this.$alert(
          "请认真做卷,勿提前交卷，至少需做" +
            this.paperInfo.minSubmissionTime / 60 +
            "分钟",
          "提示",
          {
            confirmButtonText: "确定",
            callback: (action) => {},
          }
        );
        return false;
      } else {
        this.$confirm("是否检查完毕，确认提交？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
          .then(() => {
            this.submitGet();
          })
          .catch(() => {
            return false;
          });
      }
    },
    //获取试卷基本信息
    // getHomeworkInfo() {
    //   let that = this;
    //   getHomeworkInfo(this.homeworkStudentId).then((res) => {
    //     if (res.code == 200) {
    //       that.homeworkInfo = Object.assign({}, res.data);
    //     }
    //   });
    // },
    //获取试卷信息
    getPaperData() {
      let params = {
        isStart: true,
        isTest: this.isTest == 0 ? false : true,
      };
      let id = this.homeworkStudentId;
      this.$bus.$emit("openLoading");
      getHomeworkInfo({ id, ...params })
        .then((res) => {
          this.$bus.$emit("closeLoading");
          if (res.code == 200) {
            console.log(res, "res");
            this.setPaperInfo(res);
          }
        })
        .catch(() => {
          this.$bus.$emit("closeLoading");
        });
    },
    // id=2375&isTest=0&title=计算分数测试&task&taskType&type&endTime=2020-08-31%2000%3A00%3A00
    //模拟考试获取题目
    async getTestpaper() {
      let qLength = localStorage.getItem("zj").split(",").length;
      if (qLength < 10) {
        qLength = 10;
      } else if (qLength > 30) {
        qLength = 30;
      }
      //来源
      let index = this.$store.getters.constDict.findIndex((item) => {
        return (
          item.typeCode == "QUESTION_SOURCE" && item.name == "SIMULATION_TEST"
        );
      });
      let source;
      if (index !== -1) {
        source = this.$store.getters.constDict[index].value;
      }
      let data = {
        knowledgeList: localStorage
          .getItem("zj")
          .split(",")
          .map(Number),
        difficultyList: this.$route.query.diff.split(",").map(Number),
        typeList: this.$route.query.qtype.split(",").map(Number),
        source: source ? source : "7",
        isStart: true,
        classId: this.classInfo.id,
        category: 2,
        title:
          this.$route.query.firstTest && this.$route.query.firstTest != "false"
            ? "入学测试"
            : null,
      };
      // debugger;
      this.$bus.$emit("openLoading");
      // getTestPaper(qLength, data)
      //   .then((res) => {
      //     this.$bus.$emit("closeLoading");
      //     if (res.code == 200) {
      //       this.homeworkStudentId = res.data.homeworkStudentId;
      //       this.getHomeworkInfo();
      //       this.setPaperInfo(res);
      //       this.sendMessage({
      //         code: 101,
      //         classId: this.classInfo.id,
      //         data: {
      //           bookId: this.classInfo.bookId,
      //           behavior: 2,
      //           pageId: "13",
      //           homeworkStudentId: this.homeworkStudentId,
      //           desc: { paperName: this.paperInfo.title },
      //         },
      //       });
      //     } else {
      //       this.$alert("暂无题目", "提示", {
      //         confirmButtonText: "确定",
      //         callback: () => {
      //           this.$router.replace({
      //             name: "selfImprovement",
      //           });
      //         },
      //       });
      //     }
      //   })
      //   .catch(() => {
      //     this.$bus.$emit("closeLoading");
      //   });
    },
    //薄弱点练习获取试卷
    getWeakSpotTest() {
      this.$bus.$emit("openLoading");
      // getWeakSpotTest(10, this.classInfo.id)
      //   .then((res) => {
      //     this.$bus.$emit("closeLoading");
      //     if (res.code == 200 && res.data && res.data.homeworkStudentId) {
      //       this.homeworkStudentId = res.data.homeworkStudentId;
      //       this.getHomeworkInfo();
      //       this.setPaperInfo(res);
      //       this.sendMessage({
      //         code: 101,
      //         classId: this.classInfo.id,
      //         data: {
      //           bookId: this.classInfo.bookId,
      //           behavior: 2,
      //           pageId: "26",
      //           homeworkStudentId: this.homeworkStudentId,
      //           desc: { paperName: this.paperInfo.title },
      //         },
      //       });
      //     } else {
      //       this.$message({
      //         type: "error",
      //         message: "生成试卷失败",
      //       });
      //       this.$router.replace({
      //         name: "homeworkList",
      //       });
      //     }
      //   })
      //   .catch(() => {
      //     this.$bus.$emit("closeLoading");
      //   });
    },
    //课前测试获取试卷
    getTestBeforeClass() {
      let params = {
        // classId: this.classInfo.id,
        bookId: this.classInfo.bookId,
      };
      // debugger;
      this.$bus.$emit("openLoading");
      // getTestBeforeClass(params)
      //   .then((res) => {
      //     this.$bus.$emit("closeLoading");
      //     if (res.code == 200 && res.data && res.data.homeStudentId) {
      //       this.homeworkStudentId = res.data.homeStudentId;
      //       this.getHomeworkInfo();
      //       res.data.questionList = res.data.questionVos.map((questionList) => {
      //         return questionList;
      //         // questionList.questionList.forEach(item => {
      //         //   item.answer = item.answers.map(answer => {
      //         //     return {
      //         //       id: answer.answerId,
      //         //       answer: answer.answer,
      //         //       order: answer.order
      //         //     };
      //         //   });
      //         // });
      //         // return {
      //         //   typeId: questionList.typeId,
      //         //   list: questionList.questionList
      //         // };
      //       });
      //       this.setPaperInfo(res);
      //       this.sendMessage({
      //         code: 101,
      //         classId: this.classInfo.id,
      //         data: {
      //           bookId: this.classInfo.bookId,
      //           behavior: 2,
      //           pageId: "27",
      //           homeworkStudentId: this.homeworkStudentId,
      //           desc: { paperName: this.paperInfo.title },
      //         },
      //       });
      //     } else {
      //       this.$message({
      //         type: "error",
      //         message: "生成试卷失败",
      //       });
      //       this.$router.replace({
      //         name: "homeworkList",
      //       });
      //     }
      //   })
      //   .catch(() => {
      //     this.$bus.$emit("closeLoading");
      //   });
    },
    goBack() {
      this.$router.replace({
        name: "homeworkList",
      });
    },
    setPaperQuery() {
      if (!this.$route.query.id) {
        let params = {
          id: this.homeworkStudentId,
          isTest: this.isTest,
          title: this.$route.query.title
            ? this.$route.query.title
            : this.paperInfo.title,
          type: this.$route.query.type,
          task: this.$route.query.task,
          taskType: this.$route.query.taskType,
        };
        const queryStr = Object.keys(params)
          .reduce((ary, key) => {
            if (params[key]) {
              ary.push(
                encodeURIComponent(key) + "=" + encodeURIComponent(params[key])
              );
            }
            return ary;
          }, [])
          .join("&");
        let url = `${window.location.href.split("?")[0]}?${queryStr}`;
        window.location.href = url;
      }
    },
    beforeunloadFun() {
      //
      // window.location.replace(url);
      // window.location.replaceState(window.history.state, "", url);
      return false;
      // debugger;
    },
  },
  created() {
    // window.addEventListener("beforeunload", this.beforeunloadFun);
    this.classInfo = JSON.parse(localStorage.getItem("classInfo"));
    // console.log(this.$store.dispatch);
    // this.type = this.$store.getters.qType;
    if (this.$route.query.id) {
      this.homeworkStudentId = this.$route.query.id;
      this.getPaperData();
      this.getHomeworkParams();
      // this.getHomeworkInfo();
      // this.sendMessage({
      //   code: 101,
      //   classId: this.classInfo.id,
      //   data: {
      //     bookId: this.classInfo.bookId,
      //     behavior: 2,
      //     pageId: this.isTest == 1 ? "26" : "25",
      //     homeworkStudentId: this.homeworkStudentId,
      //     desc: { paperName: this.$route.query.title },
      //   },
      // });
    } else {
      if (this.$route.query.task && this.$route.query.taskType == 1) {
        //   薄弱点练习
        this.getWeakSpotTest();
      } else if (this.$route.query.task && this.$route.query.taskType == 2) {
        //   课前测试
        this.getTestBeforeClass();
      } else {
        //模拟考试
        this.getTestpaper();
      }
    }
  },
  mounted() {
    document
      .getElementById("app")
      .addEventListener("scroll", this.handleScroll);
  },
  beforeDestroy() {
    clearInterval(this.timer);
    document
      .getElementById("app")
      .removeEventListener("scroll", this.handleScroll);
    // window.removeEventListener("beforeunload", this.beforeunloadFun);
  },
  filters: {
    filterTime(val) {
      let hours = parseInt(val / 3600);
      if (hours < 10) {
        hours = "0" + hours;
      }
      let minutes = parseInt((val % 3600) / 60);
      if (minutes < 10) {
        minutes = "0" + minutes;
      }
      let seconds = parseInt(val % 60);
      if (seconds < 10) {
        seconds = "0" + seconds;
      }
      return hours + ":" + minutes + ":" + seconds;
    },
  },
  components: {
    Header,
    Question,
    // TestQuestion,
  },
};
</script>
<style>
.el-radio__label {
  display: flex;
}
.reading-question .reading-question-list .question-title {
  background: none;
}
.reading-question .reading-question-list .read_question_style {
  background: none;
}
.reading-question .reading-question-list .bg-griy {
  background: none;
}
.reading-question .reading-question-list {
  overflow: visible;
}
</style>
